<template>
  <div class="role_container">
    <el-form :inline="true" size="small">
      <el-form-item>
        <el-input v-model="tempSearchObj.roleName" placeholder="角色名称"/>
      </el-form-item>

      <el-button type="primary" icon="el-icon-search" size="small" @click="search">查询</el-button>
      <el-button size="small"  @click="resetSearch">清空</el-button>
    </el-form>

    <div style="margin-bottom: 20px">
      <el-button type="primary" size="small" @click="addRole">添加</el-button>
      <el-button type="danger" :disabled="selectedRoles.length === 0" size="small"  @click="removeRoles()">批量删除</el-button>
    </div>

    <el-table
     size="small"
      border
      stripe
      v-loading="listLoading"
      :data="roles"
      @selection-change="handleSelectionChange">

      <el-table-column
        type="selection"
        width="55"
        align="center"
        />
      <el-table-column
        type="index"
        label="序号"
        width="80"
        align="center">
      </el-table-column>

      <!--  -->
      <el-table-column label="角色名称">
        <template v-slot:default="{row}">
          <template v-if="row.edit">
            <el-input v-model="row.roleName" class="edit-input" size="small" />
            <el-button
              class="cancel-btn"
              size="mini"
              icon="el-icon-refresh"
              type="warning"
              @click="cancelEdit(row)"
            >
              取消
            </el-button>
          </template>
          <span v-else>{{ row.roleName }}</span>
        </template>
      </el-table-column>
      

      <!-- 操作栏模块  @click="$router.push(`/acl/role/auth/${row.id}?roleName=${row.roleName}`)" 
      -->
      <el-table-column label="操作" width="300" align="center">
        <template slot-scope="{row}">
          <HintButton size="mini" type="info" icon="el-icon-info" title="分配权限"
           @click="toRoleAuth(row)" />
          <HintButton size="mini" type="primary" icon="el-icon-check" title="确定" 
          @click="updateRole(row)"  v-if="row.edit"/>
          <HintButton size="mini" type="primary" icon="el-icon-edit" title="修改角色" 
            @click="editRole(row)" v-if="!row.edit"/>
          <el-popconfirm :title="`确定删除 ${row.roleName} 吗?`" @onConfirm="removeRole(row)">
            <HintButton style="margin-left:10px" slot="reference" type="danger" size="mini" icon="el-icon-delete" 
              title="删除角色"/>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      :current-page="currentPage"
      :total="total"
      :page-size="limit"
      :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
      style="padding: 20px 0;"
      layout="prev, pager, next, jumper, ->, sizes, total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
  </div>
</template>

<script>

export default {
  name: 'RoleList',
  data() {
    return {
      listLoading: false, // 数据是否正在加载
      roles: [], // 角色列表
      total: 0, // 总记录数
      currentPage: 1, // 当前页码
      limit: 5, // 每页记录数


      tempSearchObj: { // 收集搜索条件数据
        roleName: '',
      },
      searchObj: { // 发送请求的条件参数数据
        roleName: '',
      },

      selectedRoles: [] // 所有选中的角色列表
    }
  },

  mounted() {
    this.getRoles()
  },

  methods: {
    handleSelectionChange(){
    },

  /* 1.列表数据渲染 */
    //翻页
    handleCurrentChange(val){
        // console.log(`当前页: ${val}`);
        this.getRoles(val)
    },
    //修改每页展示数据条数
    handleSizeChange(val){
        this.limit = val
        this.getRoles()
    },
    //获取角色列表
    async getRoles(page = 1){
        this.currentPage = page
        //请求搜索条件的对象searchObj,携带query参数，后台进行模糊查询返回数据
        const {limit, searchObj} = this
          //请求后开启加载效果
          this.listLoading = true
          const result = await this.$API.role.getPageList(page, limit, searchObj)
          //响应成功，关闭加载
          this.listLoading = false
          const {items, total} = result.data
          this.roles = items.map((item)=>{
             item.edit = false //标识是否显示编辑输入框的属性
             item.originRoleName = item.roleName // 缓存角色名称, 用于取消
             return item
          })
          this.total = total   
    },
    
  /* 2.模糊搜索查询 */
    //用户查询
    search(){
          this.searchObj = {...this.tempSearchObj}
          this.getRoles()
    },
    /* 清除搜索栏 */
    resetSearch(){
      this.searchObj = {
        username: ''
      }
      this.tempSearchObj = {
        username: ''
      }
      this.getRoles()
  },

  /* 3.添加和批量删除事件 */
      // 添加用户的事件
    addRole() {
      //MessageBox弹框,提示用户进行输入的对话框
      this.$prompt('请输入新的角色名称', '添加角色', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(async ({ value }) => {
        const result =await  this.$API.role.save({roleName: value})
        console.log(result);
        if(result.code == 20000 || result.code == 200){
          this.$message.success('添加角色成功')
          this.getRoles()
        }
      }).catch(() => {
          this.$message.warning('取消添加')
      })
    },
    //批量删除回调
    /*current-change事件来管理选中时触发的事件，它会传入currentRow，oldCurrentRow*/
    handleSelectionChange(selection) {
      this.selectedRoles = selection.map((item) => {
        return item.id
      })
    },
    removeRoles(){
          //MessageBox弹框
        this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
        this.$API.role.removeRoles(this.selectedRoles)
        this.$message.success('删除成功')
        this.getRoles()
      }).catch(() => {
        this.$message.info('取消删除')
      })
    },
  
  /* 4.操作栏事件回调 */
    // 修改角色 --排他操作
    editRole(row){
       this.roles.forEach((item)=>{
          item.edit = false
       })
       row.edit= true
    },
    // 取消修改
    cancelEdit(row){
        row.edit = false
        row.roleName = row.originRoleName
    },
    //确认修改
    async updateRole(row){
      const result = await  this.$API.role.updateById({id: row.id, roleName: row.roleName})
      if(result.code == 20000 || result.code == 200){
          this.$message.success(`更新角色${result.message}`)
          this.getRoles(this.currentPage)
      }
    },
    //单个角色删除
    async removeRole(row){
      const result = await this.$API.role.removeById(row.id)
      if(result.code == 20000 || result.code == 200){
          //再次获取用户信息数据,this.roles.length>1说明当前页的数据大于1,如果小于1删除后展示前面一页
          this.getRoles(this.roles.length>1?this.currentPage:this.currentPage -1);
          this.$message.success('删除成功')
      }
    },

  /* 5.跳转权限分配*/
    toRoleAuth(row){
      // this.$router.push(`/acl/role/auth/${row.id}?roleName=${row.roleName}`)
      //编程式路由导航
      this.$router.push({
           name:'RoleAuth',
          //  path:`/acl/role/auth/${row.id}`,
           params:{
              id:row.id
           },
           query:{
             roleName:row.roleName
           }
      })
    }

  }
}
</script>

<style scoped>
.role_container{
   margin: 10px 0px;
}
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>